/* Master site misc functions*/
$(document).ready(function(){
	Main.init();
	// init datepickers
	$('input[validate*=date],input[validate_on*=date]').datepicker({
	    keyboardNavigation: false,
	    autoclose: true,
	    todayHighlight: true
	}).bind('changeDate',function(){
		$(document).trigger('dateChanged',this);
	});
	// get rid of all autocompletes
	$('form,input').attr('autocomplete','off');
});

var Main = {
	// add fake events to calendar
	init:function(){
		Main.activateGuideHover();
		Main.activateTextareaResize();
	},
	activateGuideHover:function(){
		// attach highlight event to <a notification>
		$('.notification-area').hover(function(){
			var widget = $(this).attr("widget");
			$('#'+widget).addClass('highlight');
		},
		function(){
			var widget = $(this).attr("widget");
			$('#'+widget).removeClass('highlight');
		});
	},
	nav:function(page,directory,suffix,args){
		var page = page || "";
		var directory = directory || "/craftivity/";
		var suffix = suffix || ".cfm";
		var args = args || "";
		if(page == 'home'){
			page = 'dashboard';
			directory = '/';
		}
		window.location = directory+page+suffix+args;
	},
	activateTextareaResize:function(){
		try{$('textarea').off('keyup');}catch(e){/*do nothing*/}
		$('textarea').on('keyup',function(){
			Main.resizeTextarea(this);
		});
		$('textarea').each(function(){
			Main.resizeTextarea(this);
		});
	},
	resizeTextarea:function(that){
		var taLineHeight = 14;
		var $this = $(that);
		var taHeight = $this[0].scrollHeight;
		var lines = Math.floor(taHeight/taLineHeight);
		$this.attr('rows',lines);
		try{
			Placeholder.away($this);
		}catch(e){/*do nothing*/}
	},
	toggleSidebar:function(that){
		var id = that.id.replace('-minimized','');
		var otherID = 'layout-right';
		if(id == otherID){
			otherID = 'layout-left';
		}
		var $sidebar = $('#'+id);
		var $this = $(that);
		if($sidebar.hasClass('expand')){
			$('#'+otherID+'-minimized').fadeIn();
			$sidebar.removeClass('expand');
			$this.removeClass('expand');
		} else {
			$('#'+otherID+'-minimized').fadeOut();
			$('.expand').removeClass('expand');
			$sidebar.addClass('expand');
			$this.addClass('expand');
		}
	},
	func:function(cfc,method,args,prompt){
		var prompt = prompt || "";
		if(prompt != ""){
			if(confirm(prompt))	{
				window.location = '/cfcs/action.cfm?cfc='+cfc+'&method='+method+args;
			}
			return;
		} else {	
			window.location = '/cfcs/action.cfm?cfc='+cfc+'&method='+method+args;
		}
	},
	formToStruct:function($form){
		var string = decodeURIComponent($form.serialize().replace(/\+/g, '%20'));
		var split = string.split("&");
		var result = {};
		for(var i = 0; i < split.length; i++){
			var split2 = split[i].split('=');
			var name = split2[0];
			var value = "";
			if(split2.length > 1){
				value = split2[1];
			}
			if(name.length > 0){
				if(name in result){
					result[name] = result[name] + ',' + value;
				} else {
					result[name] = value;
				}
			}
		}
		return result;
	},
	urlToStruct:function(){
		var result = {};
		var urlSplit = document.URL.split('?');
		var argList = "";
		result.url = urlSplit[0];
		result.args = {};
		if(urlSplit.length > 1){
			argList = urlSplit[1];
		}
		var argArray = argList.split("&");
		for(var i = 0; i < argArray.length; i++){
			var argSplit = argArray[i].split('=');
			var name = argSplit[0];
			var value = "";
			if(argSplit.length > 1){
				value = argSplit[1];
			}
			if(name.length > 0){
				result.args[name] = value;
			}
		}
		return result;
	},
	getUrlArg:function(name){
		var result = "";
		var urlArgs = Main.urlToStruct().args;
		if(name in urlArgs){
			result = urlArgs[name];
			if(result == ""){
				result = true;
			}
		}
		return result;
	},
	toggleOptions:function(key){
		var $options = $(".widget.options");
		if($options.hasClass('hidden')){
			$options.hide();
			$options.removeClass('hidden');
			$options.slideDown(function(){
				Main.loadOptions(key,$options);
			});
		} else {
			$options.slideUp(function(){
				$options.addClass('hidden');
			});
		}
	},
	loadOptions:function(key,$options){
		var $loading = $options.find('div.unloadedOption');
		if($loading.length == 1 && !$options.hasClass('loading')){
			$options.addClass('loading');
			Ajax.run({
				method:"optionView.render"+key,
				onsuccess:function(data){
					$loading.fadeOut(function(){
						$loading.replaceWith(data);
						Validate.init();
						// scroll to and focus on first element
						var $input = $options.find('input:visible:first');
						if($input.length == 0){
							$input = $options.find('select:visible:first');
						}
						$('html, body').animate({
					        scrollTop: 0
					    }, 1000,function(){
					    	$input.focus();
					    });
					});
				}
			});
		}
	},
	timers:{},
	throttle:function(fn,key,delay,args){
		var delay = delay || 2500;
		// clear out all the timers started for this key
		for(key in Main.timers){
			clearTimeout(Main.timers[key]);
		}
		var context = this, args = args;
		Main.timers[key] = setTimeout(function () {
			delete Main.timers[key];
			fn.apply(context, args);
		}, delay);
	},
	getClientTimezone:function(){
		var offset = new Date().getTimezoneOffset();
		offset = offset / 60;
		offset = offset * -1;
		if(offset > 0){
			offset = '+' + offset;
		}
		offset += ':00';
		return offset;
	},
	getClientDST:function(){
		var today = new Date();
		if(today.dst()){
			return 1;
		} else {
			return 0;
		}
	}
};

Widget = {
	edit:function(that){
		var $that = $(that);
		var $widget = $that.closest('.widget');
		$('.widget.edit').removeClass('edit');
		$widget.addClass('edit');
		$widget.find('textarea').each(function(){
			Main.resizeTextarea(this);
		});
		var $ul = $widget.find('ul.list-input');
		if($ul.length > 0){
			$ul.find('input:last').focus();
		} else {
			var first = $widget.find('input,textarea,select')[0];
			if(typeof first === 'object'){
				$(first).selectRange($(first).val().length);
			}
		}
	},
	cancel:function(that){
		var $that = $(that);
		var $widget = $that.closest('.widget');
		$widget.removeClass('edit');
	},
	delete:function(that){
		var $this = $(that);
		if($this.hasClass('confirm')){
			var array = $this.attr('function').split('.');
			var cfc = array[0];
			var method = array[1];
			var args = array[2];
			Main.func(cfc,method,args);
		} else {
			$this.fadeOut(function(){
				$this.addClass("confirm");
				$this.text('Really Delete?')
				$this.fadeIn();
				setTimeout(function(){
					$this.fadeOut(function(){
						$this.removeClass('confirm')
						$this.text('Delete')
						$this.fadeIn();
					});
				},2000);
			});
		}

		
	}
};

var Query = {
	column:function(query,column,row){
		var row = row || 0;
		var index = -1;
		for(var i = 0; i < query.COLUMNS.length; i++){
			if(query.COLUMNS[i] == column.toUpperCase()){
				index = i;
			}
		}
		return query.DATA[row][index];
	},
	size:function(query){
		return query.DATA.length;
	}
};

$.fn.selectRange = function(start, end) {
    if(!end) end = start; 
    return this.each(function() {
        if (this.setSelectionRange) {
            this.focus();
            this.setSelectionRange(start, end);
        } else if (this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};